import traceback

from flask import Flask, jsonify

from utils.threadpool import init_thread_pool, get_thread_pool
from service.biz import async_print, biz_async_works, send_email

app = Flask(__name__)

# 初始化线程池
init_thread_pool(max_workers=10, qsize=20)


# curl 127.0.0.1:5000/demo_error_api
@app.route("/demo_error_api")
def demo_api():
    try:
        raise ValueError("模拟接口异常")
    except Exception as e:
        # Notice 同步代码: 发送邮件会导致接口有“延迟”
        send_email(
            subject="[接口异常] /demo_error_api 出错",
            content=traceback.format_exc(),
            to_addr=[""]
        )
        return jsonify({"msg": "internal error!!!"}), 500


# curl 127.0.0.1:5000/async/works
@app.route('/async/works')
def async_works():
    # 模拟请求的参数
    name = 'whw'
    ret = biz_async_works(name=name)

    # 函数 [biz_async_works] 执行时间: 4.0022 秒

    return jsonify({'ret': ret})


# curl 127.0.0.1:5000/hello_world
@app.route("/hello_world")
def hello_world():
    # Notice 被异步装饰器装饰 异步执行的代码！
    async_print()

    return jsonify({"msg": "hello_world!"})


# curl 127.0.0.1:5000/health/queue_size
@app.route("/health/queue_size")
def health():
    pool = get_thread_pool()
    return jsonify({
        "queue_size": pool.get_qsize()
    })


if __name__ == "__main__":
    app.run(debug=True)
